<?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Admin\BaseController;
use App\Http\Utils\Verify;
use Illuminate\Http\Request;
use App\Models\Admin\Menu;
use Session;
use Auth;
use Validator;

class LoginController extends BaseController
{
    public function login(Request $request)
    {
        if($request->isMethod('POST')){
            $validator = Validator::make($request->all(), [
                'user_name' => 'required',
                'password' => 'required',
                'v_code' => 'required',
            ],[
                'user_name.required' => '帐号不能为空',
                'password.required' => '密码不能为空',
                'v_code.required' => '验证码不能为空',
            ]);

            if ($validator->fails()) {
                $err = getValidatorErrorStr($validator);

                return $this->error('验证失败', $err);
            }

            $verify = new Verify($request->session());
            if (!$verify->check($request->input('v_code'), "admin_login")) {
                return $this->error('验证码过期或输入错误');
            }

            $status = Auth::guard('admin')->attempt([
                'name' =>$request->input('user_name'),
                'password' =>$request->input('password'),
            ]);

            if(!$status){
                return $this->error('用户名或密码失败');
            }

            $menus = Menu::orderBy('parent_id')->get();
            $list = array();
            foreach ($menus as $menu){
                if($menu->parent_id == 0){
                    $list[$menu->id]['id'] = $menu->id;
                    $list[$menu->id]['title'] = $menu->title;
                    $list[$menu->id]['uri'] = $menu->uri;
                    $list[$menu->id]['icon'] = $menu->icon;
                    $list[$menu->id]['parent_id'] = $menu->parent_id;
                }else{
                    if(!$menu->permission_name || Auth::guard('admin')->user()->canPerm($menu->permission_name)){
                        $list[$menu->parent_id]['items'][] = array('id'=>$menu->id,'title'=>$menu->title,'uri'=>$menu->uri,'icon'=>$menu->icon,'parent_id'=>$menu->parent_id);
                    }
                }
            }
            Session::put('meuns', $list);

            return $this->success('登录成功');
        }
        return view('admin.auth.login.login');
    }

    public function logout()
    {
        Session::flush();
        Auth::guard('admin')->logout();
        return redirect('/admin/login');
    }

    /**
     * 验证码获取
     */
    public function verify(Request $request)
    {
        $config = array(
            'fontSize' => 30,
            'length' => 4,
            'useCurve' => false,
            'useNoise' => false,
            'reset' => false
        );
        $Verify = new Verify($request->session(),$config);
        $Verify->entry("admin_login");
    }
}
